package com.iot08.admin.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * mvc拦截配置
 *
 * @version 1.0
 * @author:Rock
 * @time:2020年8月11日 11:11:27
 */
@Configuration
public class WebMvcConfigure extends WebMvcConfigurationSupport {

    @Bean
    public LoginInterceptor getLoginInterceptor() {
        return new LoginInterceptor();
    }

    /**
     * @Description: 静态文件配置
     * @time: 2020/8/20 8:56
     * @author: Rock
     * @version 1.0
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/static/");
    }

    /**
     * @Description: 拦截器注册添加
     * @time: 2020/8/20 8:57
     * @author: Rock
     * @version 1.0
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //登录拦截
        String[] loginExcludeArray = getLoginExclude();
        registry.addInterceptor(getLoginInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(loginExcludeArray);
        super.addInterceptors(registry);
    }

    /**
     * @Description: 登录拦截排除url
     * @time: 2020/8/20 8:57
     * @author: Rock
     * @version 1.0
     */
    private String[] getLoginExclude() {
        List<String> loginExclude = new ArrayList<>();
        loginExclude.add("/static/**");
        loginExclude.add("/error");
        loginExclude.add("/login");
        loginExclude.add("/doLogin");
        loginExclude.add("/code");
        loginExclude.add("/logout");
        loginExclude.add("/favicon.ico");
        loginExclude.add("/api/*");

        String[] tokenExcludeArray = new String[loginExclude.size()];
        loginExclude.toArray(tokenExcludeArray);
        return tokenExcludeArray;
    }

    /**
     * @Description: jsp文件目录配置
     * @time: 2020/8/20 9:00
     * @author: Rock
     * @version 1.0
     */
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setCache(true);
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        resolver.setContentType("text/html;charset=UTF-8");
        return resolver;
    }
}